package com.shuyixiao.javan8nv1.api;

import com.shuyixiao.javan8nv1.model.Workflow;
import com.shuyixiao.javan8nv1.core.WorkflowEngine;
import com.shuyixiao.javan8nv1.core.ExecutionContext;
import com.shuyixiao.javan8nv1.core.ExecutionResult;
import com.shuyixiao.javan8nv1.mapper.WorkflowMapper;
import com.shuyixiao.javan8nv1.mapper.NodeMapper;
import com.shuyixiao.javan8nv1.mapper.ConnectionMapper;
import com.shuyixiao.javan8nv1.model.Node;
import com.shuyixiao.javan8nv1.model.Connection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.List;

@RestController
@RequestMapping("/api/workflows")
public class WorkflowController {
    @Autowired
    private WorkflowEngine workflowEngine;
    @Autowired
    private WorkflowMapper workflowMapper;
    @Autowired
    private NodeMapper nodeMapper;
    @Autowired
    private ConnectionMapper connectionMapper;

    @GetMapping("/{workflowId}")
    public Workflow getWorkflow(@PathVariable String workflowId) {
        return workflowMapper.selectById(workflowId);
    }

    @PostMapping
    public Workflow createWorkflow(@RequestBody Workflow workflow) {
        workflowMapper.insert(workflow);
        return workflow;
    }

    @PostMapping("/{workflowId}/execute")
    public ExecutionResult executeWorkflow(@PathVariable String workflowId) {
        Workflow workflow = workflowMapper.selectById(workflowId);
        ExecutionContext context = new ExecutionContext(workflow);
        return workflowEngine.executeWorkflow(workflow, context);
    }

    @PostMapping("/full")
    public void createFullWorkflow(@RequestBody FullWorkflowDTO fullWorkflow) {
        workflowMapper.insert(fullWorkflow.getWorkflow());
        for (Node node : fullWorkflow.getNodes()) {
            node.setWorkflowId(fullWorkflow.getWorkflow().getId());
            nodeMapper.insert(node);
        }
        for (Connection conn : fullWorkflow.getConnections()) {
            conn.setWorkflowId(fullWorkflow.getWorkflow().getId());
            connectionMapper.insert(conn);
        }
    }

    @GetMapping("/full/{workflowId}")
    public FullWorkflowDTO getFullWorkflow(@PathVariable String workflowId) {
        Workflow workflow = workflowMapper.selectById(workflowId);
        List<Node> nodes = nodeMapper.selectList(
            new QueryWrapper<Node>().eq("workflow_id", workflowId)
        );
        List<Connection> connections = connectionMapper.selectList(
            new QueryWrapper<Connection>().eq("workflow_id", workflowId)
        );
        FullWorkflowDTO dto = new FullWorkflowDTO();
        dto.setWorkflow(workflow);
        dto.setNodes(nodes);
        dto.setConnections(connections);
        return dto;
    }
}
